package com.msa.msaportal.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.pluto.driver.services.portal.RenderConfig;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.founder.apps.resource.webService.NavigationServicesProxy;
import com.mgear.ldap.service.LDAPDataServiceProxy;
import com.msa.msaportal.common.web.ConstantUntil;
import com.msa.msaportal.common.web.ResponseUtils;
import com.msa.msaportal.common.web.WebserviceUtils;
import com.msa.msaportal.entity.PortalCssEntity;
import com.msa.msaportal.entity.PortalExample;
import com.msa.msaportal.entity.PortalPage;
import com.msa.msaportal.entity.Portalfooter;
import com.msa.msaportal.entity.PortalheaderEntity;
import com.msa.msaportal.entity.PortletEntity;
import com.msa.msaportal.entity.Template;
import com.msa.msaportal.service.IPortalCssEntityService;
import com.msa.msaportal.service.IPortalExampleService;
import com.msa.msaportal.service.IPortalPageService;
import com.msa.msaportal.service.ITemplateService;

@Controller
@RequestMapping("/portal")
public class PortalShowController {

	@Resource(name = "portalManager")
	private IPortalExampleService portalManager;
	@Resource(name = "portalcssManager")
	private IPortalCssEntityService portalcssManager;
	@Resource(name = "templateManager")
	private ITemplateService templateManager;
	@Resource(name = "pageManager")
	private IPortalPageService pageManager;

	/**
	 * 发布portal实例展示数据
	 * 
	 * @param model
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/showPortal.do")
	public void showPortal(HttpServletRequest request, HttpServletResponse response, HttpSession session, ModelMap model) throws IOException {

//		String role_idDes = (String) session.getAttribute("productRoleid");
//		System.out.println(role_idDes);
//		String[] str = new String[role_idDes.split(",").length];
//		role_idDes = role_idDes.substring(0, role_idDes.length() - 1);
//		str = role_idDes.split(",");
		List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();
//		for (int k = 0; k < str.length; k++) {
//			if (str[k] != null && str[k] != "") {
//				System.out.println(str[k]);
//				Integer role_id = Integer.valueOf(str[k]);
//				String userId = (String) session.getAttribute("loginUserId");
//				// 获得首页权限
//				List<PortalExample> list = portalManager.getPortal();
//				for (int i = 0; i < list.size(); i++) {
//					PortalExample pe = list.get(i);
//					PortalCssEntity cssentity = pe.getPortalcss();
//					String csssourceid = cssentity.getCsourceId();
//					Template templateEntity = pe.getTemplate();
//					Integer template_id = templateEntity.getTemplate_id();
//					List<PortalPage> portalPage = pageManager.getPageListByPortal(pe);
//
//					Integer PortlePageId = 0;
//					for (int j = 0; j < portalPage.size(); j++) {
//						PortalPage page = portalPage.get(j);
//						if (page.getPageCode().equals(ConstantUntil.HOMEPAGECODE)) {
//							PortlePageId = page.getPageId();
//						}
//					}
//					System.out.println("++++  " + PortlePageId + role_id);// 924
//																			// 48
//					List<PortletEntity> portletlist = pageManager.getByRoleId(PortlePageId, role_id);
//					System.out.println("portletlist " + portletlist);
//					for (int j = 0; j < portletlist.size(); j++) {
//						Map<String, Object> map = new HashMap<String, Object>();
//
//						map.put("portletName", portletlist.get(j).getPortletName());
//						map.put("portletId", portletlist.get(j).getPortletId());
//						map.put("pagerow", portletlist.get(j).getPagerow());
//						String urlafter = "";
//						if (portletlist.get(j).getPortletview().indexOf("?") == -1) {
//							urlafter = "?userId=" + userId + "&styleId=" + csssourceid + "&templateId=" + template_id;
//						} else {
//							urlafter = "&userId=" + userId + "&styleId=" + csssourceid + "&templateId=" + template_id;
//						}
//						map.put("viewUrl", portletlist.get(j).getPortletview() + urlafter);
//						map.put("portletorder", portletlist.get(j).getPortletorder());
//						if (!listMap.contains(map)) {
//							listMap.add(map);
//						}
//
//					}
//
//				}
//			}
//		}
		
	
		String userId = (String) session.getAttribute("loginUserId");
		// 获得首页权限
		List<PortalExample> list = portalManager.getPortal();
		for (int i = 0; i < list.size(); i++) {
			PortalExample pe = list.get(i);
			PortalCssEntity cssentity = pe.getPortalcss();
			String csssourceid = cssentity.getCsourceId();
			Template templateEntity = pe.getTemplate();
			Integer template_id = templateEntity.getTemplate_id();
			List<PortalPage> portalPage = pageManager.getPageListByPortal(pe);

			Integer PortlePageId = 0;
			for (int j = 0; j < portalPage.size(); j++) {
				PortalPage page = portalPage.get(j);
				if (page.getPageCode().equals(ConstantUntil.HOMEPAGECODE)) {
					PortlePageId = page.getPageId();
				}
			}									
			List<PortletEntity> portletlist = pageManager.getPortletlistByPageId(PortlePageId);
			System.out.println("portletlist " + portletlist);
			for (int j = 0; j < portletlist.size(); j++) {
				Map<String, Object> map = new HashMap<String, Object>();

				map.put("portletName", portletlist.get(j).getPortletName());
				map.put("portletId", portletlist.get(j).getPortletId());
				map.put("pagerow", portletlist.get(j).getPagerow());
				String urlafter = "";
				if (portletlist.get(j).getPortletview().indexOf("?") == -1) {
					urlafter = "?userId=" + userId + "&styleId=" + csssourceid + "&templateId=" + template_id;
				} else {
					urlafter = "&userId=" + userId + "&styleId=" + csssourceid + "&templateId=" + template_id;
				}
				map.put("viewUrl", portletlist.get(j).getPortletview() + urlafter);
				map.put("portletorder", portletlist.get(j).getPortletorder());
				if (!listMap.contains(map)) {
					listMap.add(map);
				}

			}

		}

		JSONArray json = JSONArray.fromObject(listMap);
		ResponseUtils.renderJson(response, json.toString());
	}

	/**
	 * 发布portal实例 加载样式和模板
	 * 
	 * @param model
	 * @throws IOException
	 */
	@RequestMapping("/showPortalPage.do")
	public String showPortalPage(HttpServletRequest request, HttpServletResponse response, HttpSession session, ModelMap model) throws IOException {

		List<PortalExample> list = portalManager.getPortal();
		for (int i = 0; i < list.size(); i++) {
			PortalExample pe = list.get(i);
			model.addAttribute("portal_id", pe.getPortal_id());

			// 获取样式文件
			PortalCssEntity py = portalManager.showPortalCss(pe.getPortalcss().getCssId());
			String cssPath = py.getCssPath();
			model.addAttribute("cssPath", cssPath);

			// 获取模板文件
			Template te = portalManager.showPortalTemp(pe.getTemplate().getTemplate_id());
			String templatePath = te.getTemplate_path();
			model.addAttribute("templatePath", templatePath);
			// 获取footerContent

			String footerContent;
			if (te.getFooter() == null || te.getFooter().equals("")) {
				footerContent = "";

			} else {
				Integer footerResId = te.getFooter().getFooterres_id();
				Portalfooter portalfooter = portalManager.getFooterContent(footerResId);
				footerContent = portalfooter.getFooter_content().replace("<p>", "");
				footerContent = footerContent.replace("</p>", "");
				footerContent = footerContent.trim();
			}
			model.addAttribute("footerContent", footerContent);

			// 获取 Header logo_url
			String logoUrl;
			if (te.getHeader() == null || te.getHeader().equals("")) {
				logoUrl = "";
			} else {
				Integer headerresid = te.getHeader().getHeaderresid();
				PortalheaderEntity portalheaderEntity = portalManager.getPortalheaderEntity(headerresid);
				logoUrl = portalheaderEntity.getLogo_url();
			}
			model.addAttribute("logoUrl", logoUrl);
			model.addAttribute("userName", request.getSession().getAttribute("userName"));
		}
		return "/Basic";
	}

	/**
	 * 预览portal实例展示数据
	 * 
	 * @param model
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/previewPortal.do")
	public void previewPortal(HttpServletRequest request, HttpServletResponse response, HttpSession session, String portal_id, ModelMap model) throws IOException {

		String userId = (String) session.getAttribute("loginUserId");
		// 根据portal_id 查询要展示的首页
		PortalExample pe = portalManager.findByPortalid(portal_id);
		List<PortalPage> portalPage = pageManager.getPageListByPortal(pe);
		Integer PortlePageId = 0;
		for (int j = 0; j < portalPage.size(); j++) {
			PortalPage page = portalPage.get(j);
			if (page.getPageCode().equals(ConstantUntil.HOMEPAGECODE)) {
				PortlePageId = page.getPageId();
			}
		}
		List<PortletEntity> portletlist = pageManager.getPortletlistByPageId(PortlePageId);
		List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();
		PortalCssEntity cssentity = pe.getPortalcss();
		Template templateEntity = pe.getTemplate();
		Integer template_id = templateEntity.getTemplate_id();
		String csssourceid = cssentity.getCsourceId();
		for (int j = 0; j < portletlist.size(); j++) {
			Map<String, Object> map = new HashMap<String, Object>();

			PortletEntity pee = portletlist.get(j);
			map.put("portletName", pee.getPortletName());
			map.put("portletId", pee.getPortletId());
			map.put("pagerow", pee.getPagerow());
			String urlafter = "";
			if (portletlist.get(j).getPortletview().indexOf("?") == -1) {
				urlafter = "?userId=" + userId + "&styleId=" + csssourceid + "&templateId=" + template_id;
			} else {
				urlafter = "&userId=" + userId + "&styleId=" + csssourceid + "&templateId=" + template_id;
			}
			map.put("viewUrl", pee.getPortletview() + urlafter);
			map.put("portletorder", pee.getPortletorder());
			listMap.add(map);
		}
		JSONArray json = JSONArray.fromObject(listMap);
		response.getWriter().write(json.toString());

	}

	/**
	 * 预览portal实例加载样式和模板
	 * 
	 * @param model
	 * @throws IOException
	 */
	@RequestMapping("/previewPortalPage.do")
	public String previewPortalPage(HttpServletRequest request, HttpServletResponse response, String portal_id, ModelMap model) throws IOException {
		PortalExample pe = portalManager.findByPortalid(portal_id);
		model.addAttribute("portal_id", pe.getPortal_id());
		// 获取样式文件
		PortalCssEntity py = portalManager.showPortalCss(pe.getPortalcss().getCssId());
		String cssPath = py.getCssPath();
		model.addAttribute("cssPath", cssPath);

		// 获取模板文件
		Template te = portalManager.showPortalTemp(pe.getTemplate().getTemplate_id());
		String templatePath = te.getTemplate_path();
		model.addAttribute("templatePath", templatePath);
		// 获取footerContent
		// Integer footerResId= te.getFooter().getFooterres_id();
		String footerContent;
		if (te.getFooter() == null || te.getFooter().equals("")) {
			footerContent = "";

		} else {
			Integer footerResId = te.getFooter().getFooterres_id();
			Portalfooter portalfooter = portalManager.getFooterContent(footerResId);
			footerContent = portalfooter.getFooter_content().replace("<p>", "");
			footerContent = footerContent.replace("</p>", "");
			footerContent = footerContent.trim();
		}
		model.addAttribute("footerContent", footerContent);
		// 获取 Header logo_url

		String logoUrl;
		if (te.getHeader() == null || te.getHeader().equals("")) {
			logoUrl = "";
		} else {
			Integer headerresid = te.getHeader().getHeaderresid();
			PortalheaderEntity portalheaderEntity = portalManager.getPortalheaderEntity(headerresid);
			logoUrl = portalheaderEntity.getLogo_url();
		}
		model.addAttribute("logoUrl", logoUrl);
		// model.addAttribute("userName",request.getSession().getAttribute("userName"));

		return "/preview";
	}

	/**
	 * portal实例菜单展示
	 * 
	 * @param model
	 * @param portal_id
	 * @param session
	 * @throws Exception
	 */
	@RequestMapping("/showMenu.do")
	public void showMenu(HttpServletRequest request, HttpServletResponse response, HttpSession session, String portal_id, ModelMap model) throws Exception {

		String userId = (String) session.getAttribute("loginUserId");

		// 最终接口
		PortalExample pe = portalManager.findByPortalid(portal_id);
		String templateId = pe.getTemplate().getTsource_id();

		String jsonNew = "{'userId':'" + userId + "','templateId':'" + templateId + "' }";
		// System.out.println("----------------"+userId+"******"+templateId);
		/*
		 * String jsonNew =
		 * "{'userId':'14260197911261329','templateId': '1114'}";
		 */
		NavigationServicesProxy NS = new NavigationServicesProxy();
		String jjson = NS.queryNavigation(jsonNew);

		/*
		 * LDAPDataServiceProxy lsp = new LDAPDataServiceProxy(); String navjson
		 * ="{'userId':'"+userId+"'}"; String jjson =
		 * lsp.userQueryServices_userQueryRoles(navjson);
		 */
		JSONObject json1 = JSONObject.fromObject(jjson);

		System.out.println("++++++++++++++++++++++");
		System.out.println(json1);
		if (json1.get("result").equals("1")) {
			JSONArray jsonArray = json1.getJSONObject("datas").getJSONObject("table").getJSONArray("row");
			// System.out.println(jsonArray.toString());
			LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>();
			HashMap<String, Object> map1 = new HashMap<String, Object>();
			int flag=0;
			for (int i = 0; i < jsonArray.size(); i++) {
				JSONObject jsonn = (JSONObject) jsonArray.get(i);
				String businessType = jsonn.getString("businessType").trim();
				if (("CMP_001_R00011".equals(jsonn.getString("roleCode"))) || ("CMP_001_R00005".equals(jsonn.getString("roleCode")))) {
					flag=1;
				}

				if (!map.containsKey(businessType)) {
					JSONObject jo = new JSONObject();
					jo.put("one", jsonn);
					map.put(businessType, jo);
				}

				if (jsonn.containsKey("appName") && !jsonn.getString("appName").equals("") && !jsonn.getString("appName").equals("新门户")) {

					String appName = jsonn.getString("appName").trim();
					JSONObject j = (JSONObject) map.get(businessType);
					if (!map1.containsKey(appName)) {
						JSONArray ja = null;
						if (j.get("twoList") != null) {
							ja = j.getJSONArray("twoList");
							ja.add(jsonn);
						} else {
							ja = new JSONArray();
							ja.add(jsonn);
						}
						j.put("twoList", ja);
						map.put(businessType, j);
						map1.put(appName, appName);
					}
				}
			}
			JSONArray jsonArrayList = new JSONArray();
			for (Entry<String, Object> entry : map.entrySet()) {
				JSONObject json2 = (JSONObject) entry.getValue();
				jsonArrayList.add(json2);
			}
			if(flag==1){
				JSONObject QXJson=new JSONObject();
				QXJson.put("businessType", "磁贴权限管理");
				QXJson.put("url", "");
				QXJson.put("one", QXJson);
				jsonArrayList.add(QXJson);
			}
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("list", jsonArrayList);
			// System.out.println(jsonObject.toString());
			response.getWriter().write(jsonObject.toString());
		} else {
			response.getWriter().write("");
		}
	}

}
